import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { USER_ROLE } from '@/constants'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { guest: true }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/auth/Register.vue'),
    meta: { guest: true }
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('@/views/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/create-post',
    name: 'create-post',
    component: () => import('@/views/CreatePost.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/post/:id',
    name: 'post-detail',
    component: () => import('@/views/PostDetail.vue')
  },
  {
    path: '/hot',
    name: 'hot',
    component: () => import('@/views/Hot.vue')
  },
  {
    path: '/my-posts',
    name: 'my-posts',
    component: () => import('@/views/MyPosts.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/favorites',
    name: 'favorites',
    component: () => import('@/views/Favorites.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/messages',
    name: 'messages',
    component: () => import('@/views/Messages.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/chat',
    name: 'chat',
    component: () => import('@/views/ChatRoom.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/tech',
    name: 'tech',
    component: () => import('@/views/TechDiscussion.vue')
  },
  {
    path: '/life',
    name: 'life',
    component: () => import('@/views/LifeSharing.vue')
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/Search.vue')
  },
  // 管理员路由
  {
    path: '/admin',
    name: 'admin',
    component: () => import('@/views/admin/AdminLayout.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: 'post-audit',
        name: 'post-audit',
        component: () => import('@/views/admin/PostAudit.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取token
  const token = localStorage.getItem('accessToken')
  const userInfoStr = localStorage.getItem('userInfo')
  
  // 访客页面处理
  if (to.meta.guest && token) {
    next('/')
    return
  }
  
  // 需要认证的页面处理
  if (to.meta.requiresAuth && !token) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  // 管理员页面处理
  if (to.meta.requiresAdmin) {
    // 解析用户信息和角色
    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        const role = userInfo.role || ''
        
        console.log('正在检查管理员权限:', {
          角色: role,
          用户名: userInfo.username,
          路径: to.fullPath
        })
        
        // 检查是否具有管理员或超级管理员角色
        const isAdmin = 
          role === USER_ROLE.ADMIN || 
          role === USER_ROLE.SUPER_ADMIN ||
          role.toLowerCase().includes('admin') || 
          role.toLowerCase().includes('super');
        
        if (!isAdmin) {
          console.warn('访问管理员页面被拒绝: 角色不足', role)
          next('/')
          return
        }
        
        console.log('管理员权限验证通过，准许访问:', to.fullPath)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        next('/')
        return
      }
    } else {
      console.warn('访问管理员页面被拒绝: 未找到用户信息')
      next('/')
      return
    }
  }
  
  next()
})

export default router 